package sit.mycatalog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sit.mycatalog.web.mbean.LoginBean;

/**
 * Servlet Filter implementation class SessionFilter
 */
//@WebFilter("/admin/*")
public class SessionFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SessionFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpSession session = httpRequest.getSession(true);
		
		LoginBean loginBean = (LoginBean)session.getAttribute("loginBean");
		
		if((!httpRequest.getRequestURI().endsWith("/login.jsf")) && ((loginBean == null) || !loginBean.getLoginpass())) {
//			System.out.println("forward to login");
			((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath() + "/admin/login.jsf");
		} else {
//			System.out.println("session validate");
			chain.doFilter(request, response);
		}
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
